//
//  LSRefreshControlView.swift
//  新浪微博---01次
//
//  Created by 李宗帅 on 16/5/11.
//  Copyright © 2016年 LS. All rights reserved.
//

import UIKit
//定义状态的枚举,一共出现三种状态: 正常  刷新  释放
enum LSRefreshControlViewType: Int{
    case Normal = 0
    
    case Pulling = 1
    
    case Loading = 2
}

class LSRefreshControlView: UIControl {
    
    //定义一个属性 来记录我们的状态
    var type:LSRefreshControlViewType = .Normal {
        didSet {
            
            switch type {
            case .Normal: mesageLabel.text = "下拉刷新"
                arrowImageView.hidden = false
                
                loading.hidden = true
                
                loading.stopAnimating()
                
                UIView.animateWithDuration(0.5, animations: { () -> Void in
                    self.arrowImageView.transform = CGAffineTransformIdentity
                })
            case .Pulling: mesageLabel.text = "释放更新"
            UIView.animateWithDuration(0.5, animations: { () -> Void in
                
                self.arrowImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI - 0.01))
            })
            case .Loading: mesageLabel.text = "加载中......"
                
                var inset = scrollView!.contentInset.top
                
                inset = inset + self.frame.height
                
                scrollView?.contentInset.top = inset
                //变成加载中之后 应该让控制器加载数据 可以通过回调方法实现
            
            //下边这个方法能够监听自己本身的一个改变,然后触发所有用到这个控件的控制器内的方法
                sendActionsForControlEvents(UIControlEvents.ValueChanged)
                
                //加载的时候让箭头隐藏 让菊花显示
                arrowImageView.hidden = true
                
                loading.hidden = false
                
                loading.startAnimating()
            }
        }
    }

    func endRefreshing(){

        
        //下拉刷新的状态才让他往回走
        if type == .Loading {
            
            var inset = scrollView!.contentInset.top
            
            inset = inset - self.frame.height
            
            scrollView?.contentInset.top = inset
        }
        
                type = .Normal
    }
    
    
    var scrollView: UIScrollView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //把这个添加到哪里 就得到谁的 方法
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
        scrollView = newSuperview as? UIScrollView
        
        //添加KVO监听
        scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
    }
    
    //实现监听的方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //拖拽的时候判断下 如果在拖拽  只有两种状态 正常和释放   不拖拽的时候 有一种 就是加载
        if scrollView!.dragging {
            
            if scrollView?.contentOffset.y < -130 && type == .Normal {
                
                type = .Pulling
                
            } else if scrollView?.contentOffset.y > -130 && type == .Pulling {
                
                type = .Normal
                
            }
            
        } else {
            if scrollView?.contentOffset.y < -130 && type == .Pulling {
                
                type = .Loading
            }
        }
        
        
    }
    private func setupUI(){
        
        backgroundColor = UIColor.yellowColor()
        
        //初始化一个宽高
        var frame = self.frame
        frame.size = CGSizeMake(UIScreen.mainScreen().bounds.size.width, 44)
        
        //调整显示的位置
        frame.origin.y = frame.origin.y - 44
        
        self.frame = frame
        
        addSubview(arrowImageView)
        addSubview(loading)
        addSubview(mesageLabel)
        
        arrowImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            
            make.centerY.equalTo(self.snp_centerY)
        }
        
        mesageLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(arrowImageView.snp_right)
            
            make.centerY.equalTo(self.snp_centerY)
        }
        
        
        loading.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowImageView.center)
            
        }
        
    }
    
    //懒加载
    private lazy var arrowImageView: UIImageView = {
        
        let img = UIImageView()
        
        
        img.image = UIImage(named: "tableview_pull_refresh")
        
        
        return img
    }()
    
    private lazy var mesageLabel:UILabel = {
        
        let label = UILabel()
        
        label.font = UIFont.systemFontOfSize(16)
        
        label.textColor = UIColor.darkGrayColor()
        
        
        label.textAlignment = .Center
        
        
        label.text = "下拉刷新"
  
        return label
    }()
    
    
    //懒加载菊花
    private lazy var loading:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
}
